Plus one¶
Time: O(N); Space: O(1); easy
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation:
The array represents the integer 123.
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation:
The array represents the integer 4321.
[1]:
class Solution1():
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 1
for i in reversed(range(len(digits))):
digits[i] += carry
carry = digits[i] // 10
digits[i] %= 10
if carry:
digits = [1] + digits
return digits
[5]:
s = Solution1()
digits = [1, 2, 3]
assert s.plusOne(digits) == [1, 2, 4]
digits = [4, 3, 2, 1]
assert s.plusOne(digits) ==[4, 3, 2, 2]
[6]:
class Solution2():
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits = [str(x) for x in digits]
num = int(''.join(digits)) + 1
return [int(x) for x in str(num)]
[7]:
s = Solution2()
digits = [1, 2, 3]
assert s.plusOne(digits) == [1, 2, 4]
digits = [4, 3, 2, 1]
assert s.plusOne(digits) ==[4, 3, 2, 2]